package com.mall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.product.entity.po.ProductCategory;
import com.mall.product.entity.vo.CategoryTreeNodeVO;
import com.mall.product.mapper.ProductCategoryMapper;
import com.mall.product.service.ProductCategoryService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {

    @Override
    public List<CategoryTreeNodeVO> getCategoryTree() {
        // 1. 查询所有启用的分类
        List<ProductCategory> categories = this.list(
            new LambdaQueryWrapper<ProductCategory>()
                .eq(ProductCategory::getStatus, 1)
                .orderByAsc(ProductCategory::getSort)
        );

        if (CollUtil.isEmpty(categories)) {
            return Collections.emptyList();
        }

        // 2. 转换为树节点VO
        List<CategoryTreeNodeVO> nodeVOs = categories.stream().map(category -> {
            CategoryTreeNodeVO vo = new CategoryTreeNodeVO();
            vo.setId(category.getId());
            vo.setName(category.getName());
            vo.setParentId(category.getParentId());
            vo.setLevel(category.getLevel());
            vo.setSort(category.getSort());
            vo.setStatus(category.getStatus());
            return vo;
        }).toList();

        // 3. 构建树结构
        Map<Long, CategoryTreeNodeVO> nodeMap = nodeVOs.stream()
            .collect(Collectors.toMap(CategoryTreeNodeVO::getId, vo -> vo));

        List<CategoryTreeNodeVO> rootNodes = new ArrayList<>();

        for (CategoryTreeNodeVO node : nodeVOs) {
            if (node.getParentId() == 0) {
                // 一级分类
                rootNodes.add(node);
            } else {
                // 查找父节点
                CategoryTreeNodeVO parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        // 4. 对各级节点按排序字段排序
        rootNodes.sort(Comparator.comparing(CategoryTreeNodeVO::getSort));
        for (CategoryTreeNodeVO rootNode : rootNodes) {
            if (rootNode.getChildren() != null) {
                rootNode.getChildren().sort(Comparator.comparing(CategoryTreeNodeVO::getSort));
            }
        }

        return rootNodes;
    }
}